<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\enum\OeCodeEnum;
use app\model\ClientAccountModel;
use app\model\CrontabTaskModel;
use app\model\OeMaterialPicDailyReportExtModel;
use app\model\OeMaterialPicDailyReportModel;
use app\model\OePicModel;
use app\service\client\AccountService;
use app\service\CrontabTaskService;
use app\service\ocean\FinanceService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

class OeMaterialPicDailyReportWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    // 已测试
    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_material_pic_daily_report_work');
        $this->setDescription('巨量引擎-图片素材日流水拉取');
        $this->addArgument('type', Argument::REQUIRED, '类型  1：昨日报表 2：自定义时间');
        $this->addArgument('start_date', Argument::OPTIONAL, '开始日期');
        $this->addArgument('end_date', Argument::OPTIONAL, '结束日期');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======巨量引擎-素材日流水拉取开始' . date('Y-m-d H:i:s', time()) . '=======');
        $type = $input->getArgument('type');
        $startDate = $input->getArgument('start_date');
        $endDate = $input->getArgument('end_date');

        $dateList = [];
        if ($type == OceanEnum::YESTERDAY) {
            $yesterDay = date('Y-m-d', strtotime('-1 day'));
            $dateList[] = $yesterDay;
        } elseif ($type == OceanEnum::CUSTOM_DAY) {
            if (! $startDate || ! $endDate) {
                $output->writeln('===========开始时间，结束时间都必须存在！===========');
                return;
            }

            if ($startDate > $endDate) {
                $output->writeln('===========开始时间必须小于结束时间！===========');
                return;
            }

            $dateList = createDateRange($startDate, $endDate);
        }

        if (! $dateList) {
            logss($this->getDescription(), $this->getName(), 'date list is empty!');
            return;
        }

        $redis = Cache::store('redis')->handler();
        $redisKey = (new RefreshYesterdayPicReportListWork())->getListKey(CommonEnum::OE_MEDIA);
        for ($i = 0; $i < 100; ++$i) {
            $account = $redis->lPop($redisKey);
            if ($account) {
                $account = explode('_', $account);
                $advertiserId = $account[0];
                $execNum = intval($account[1]);
                $this->clientAccountInfo = $this->_getClientAccountInfo($advertiserId);

                if (! $this->clientAccountInfo) {
                    $err = ['params' => ['token' => '', 'advertiserId' => $advertiserId], 'response' => ['oe client account info is empty！']];
                    $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                    logss($this->getDescription(), $this->getName(), $err);
                    CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                    return;
                }

                foreach ($dateList as $nowDate) {
                    $page = 0;
                    while (true) {
                        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                        if (! $token) {
                            CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, 'token获取失败');
                            break;
                        }
                        ++$page;
                        $result = $this->_getServiceMaterialDailyReport($token, $advertiserId, $nowDate, $nowDate, $page);
                        if (! $result) {
                            $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => FinanceService::getError(0)];
                            $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                            logss($this->getDescription(), $this->getName(), $err);
                            CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                            break;
                        }

                        if (isset($result['code']) && $result['code'] != OeCodeEnum::SUCCESS) {
                            $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => $result];
                            $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                            logss($this->getDescription(), $this->getName(), $err);
                            CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                            break;
                        }

                        $list = $result['data']['list'];
                        if (count($list) == 0) {
                            break;
                        }

                        foreach ($list as $v) {
                            $materialId = strval($v['dimensions']['material_id']);
                            $statDate = intval(date('Ymd', strtotime($nowDate)));
                            $materialDailyReportInfo = $this->_getMaterialDailyReportInfo($advertiserId, $statDate, $materialId);

                            if ($materialDailyReportInfo) {
                                if (! $this->_isReportDataUpdate($materialDailyReportInfo, $v)) {
                                    $result = $this->_updateMaterialData($materialDailyReportInfo['id'], $v);
                                }
                            } else {
                                $result = $this->_insertMaterialData($advertiserId, $statDate, $v);
                            }
                        }
                    }
                }

            } else {
                try {
                    CrontabTaskService::setSingleTask($this);
                } catch (\Exception $e) {
                    $output->writeln($e->getMessage());
                }
            }

        }

        $output->writeln('=======巨量引擎-素材日流水拉取结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取账户信息.
     * @param string $advertiserId 账户ID
     * @throws
     */
    private function _getClientAccountInfo(string $advertiserId = ''): array
    {
        $info = (new ClientAccountModel())->where('advertiser_id', $advertiserId)->field(true)->find();

        if (! $info) {
            return [];
        }
        return $info->toArray();
    }

    /**
     * 获取图片信息.
     * @throws
     */
    private function _getOePicInfo(string $advertiserId = '', string $materialId = ''): array
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['material_id', '=', $materialId],
        ];

        $info = (new OePicModel())->where($where)->field(true)->find();

        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 插入广告素材流水信息.
     * @param string $advertiserId 账户ID
     * @param array $info 信息数据
     */
    private function _insertMaterialData(string $advertiserId = '', int $statDate = 0, array $info = []): bool
    {
        try {
            Db::startTrans();
            $materialId = strval($info['dimensions']['material_id']);

            $videoInfo = $this->_getOePicInfo($advertiserId, $materialId);

            $cost = $info['metrics']['cost'];
            $signature = '';
            if (! empty($videoInfo)) {
                $signature = $videoInfo['signature'];
            }

            $data = [
                'company_id' => $this->clientAccountInfo['company_id'],
                'client_id' => $this->clientAccountInfo['client_id'],
                'account_id' => $this->clientAccountInfo['id'],
                'advertiser_id' => $advertiserId,
                'stat_date' => $statDate,
                'pic_id' => $materialId,
                'signature' => $signature,
                'cost' => $cost,
                'create_time' => time(),
            ];

            $insertId = (new OeMaterialPicDailyReportModel())->insertGetId($data);
            if ($insertId <= 0) {
                Db::rollback();
                return false;
            }

            $extData = [
                'company_id' => $this->clientAccountInfo['company_id'],
                'client_id' => $this->clientAccountInfo['client_id'],
                'account_id' => $this->clientAccountInfo['id'],
                'report_id' => $insertId,
                'advertiser_id' => $advertiserId,
                'stat_date' => $statDate,
                'content' => json_encode($info, JSON_UNESCAPED_UNICODE),
                'create_time' => time(),
            ];

            $extInsertId = (new OeMaterialPicDailyReportExtModel())->insertGetId($extData);

            if ($extInsertId <= 0) {
                Db::rollback();
                return false;
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 判断是否需要更新.
     * @param array $oldData 旧数据
     * @param array $newData 新数据
     */
    private function _isReportDataUpdate(array $oldData = [], array $newData = []): bool
    {
        $metrics = $newData['metrics'];
        $one = $oldData['cost'] == $metrics['cost'];

        if ($one) {
            return true;
        }
        return false;
    }

    /**
     * 修改广告素材流水信息.
     * @param int $id 主键ID
     * @param array $info 信息数据
     */
    private function _updateMaterialData(int $id = 0, array $info = []): bool
    {
        try {
            Db::startTrans();

            $cost = $info['metrics']['cost'];

            $data = [
                'cost' => $cost,
                'update_time' => time(),
            ];

            $insertId = (new OeMaterialPicDailyReportModel())->where('id', $id)->update($data);

            if ($insertId <= 0) {
                Db::rollback();
                return false;
            }

            $extData = [
                'content' => json_encode($info, JSON_UNESCAPED_UNICODE),
                'update_time' => time(),
            ];

            $extInsertId = (new OeMaterialPicDailyReportExtModel())->where('report_id', $id)->update($extData);

            if ($extInsertId <= 0) {
                Db::rollback();
                return false;
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * @param string $advertiserId 账户ID
     * @param int $statDate 时间
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function _getMaterialDailyReportInfo(string $advertiserId = '', int $statDate = 0, string $materialId = ''): array
    {
        $where = [
            ['stat_date', '=', $statDate],
            ['advertiser_id', '=', $advertiserId],
            ['pic_id', '=', $materialId],
        ];

        /*$videoInfo = $this->_getOeVideoInfo($advertiserId, $videoId);

        if ($videoInfo) {
            $where['signature'] = $videoInfo['signature'];
        }*/

        $fields = [
            '*',
            "CONCAT(stat_date,'_',advertiser_id,'_',pic_id,'_',signature) as k",
        ];

        $info = (new OeMaterialPicDailyReportModel())->where($where)->field($fields)->find();

        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 获取获取广告素材流水信息.
     * @param string $token token
     * @param string $advertiserId 账户ID
     * @param string $startDate 开始时间
     * @param string $endDate 结束 时间
     * @return bool|mixed|string
     */
    private function _getServiceMaterialDailyReport(string $token = '', string $advertiserId = '', string $startDate = '', string $endDate = '', int $page = 1)
    {
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];

        $params = [
            'advertiser_id' => $advertiserId,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'page' => $page,
            'page_size' => OceanEnum::MAX_MATERIAL_PAGE_SIZE,
            'group_by' => ['STAT_GROUP_BY_MATERIAL_ID', 'STAT_GROUP_BY_TIME_DAY'],
            'filtering' => $this->_getFiltering(),
        ];

        return FinanceService::getMaterialIntegratedDailyReport($headers, $params);
    }

    /**
     * 获取过滤字段.
     * @return string[]
     */
    private function _getFiltering(): array
    {
        return ['image_mode' => ['CREATIVE_IMAGE_MODE_SMALL', 'CREATIVE_IMAGE_MODE_LARGE', 'CREATIVE_IMAGE_MODE_GROUP', 'CREATIVE_IMAGE_MODE_LARGE_VERTICAL', 'TOUTIAO_SEARCH_AD_IMAGE']];
    }
}
